uniform sampler2D mainTexture;
uniform sampler2D blurTexture;
uniform float windowWidth;
uniform float  windowHeight;

uniform float exposure;
uniform float gamma;
uniform float contrast;
uniform float brightness;
uniform float bloomAmount;

const float MIDDLE_GREY = 0.72;
const float FUDGE = 0.001;
const float L_WHITE = 1.5;

varying vec2 texCoord;

/** Tone mapping function 
  @note Only affects rgb, not a
  @param inColour The HDR colour
  @param lum The scene lumninence 
  @returns Tone mapped colour
 */
vec3 toneMap(in vec3 inColour, in float lum)
{
	// From Reinhard et al
	// Initial luminence scaling (equation 2)
	inColour*= MIDDLE_GREY / (FUDGE + lum);
	// Control white out (equation 4 nom)
	inColour*= (1.0 + inColour/ L_WHITE);
	// Finalmapping (equation 4 denom)
	inColour/= (1.0 + inColour);
	return inColour;
}

void main()
{
	float expo = exp(1.0-exposure);
	float HDRgam =exp(-gamma); 

	vec3 color = vec3(0.0);
	vec3 sample;
	float sideCoeffs[3];
	sideCoeffs[0]=	0.2;
	sideCoeffs[1] = 0.6;
	sideCoeffs[2] = 0.2;

	//for(int y=-1;y<=1;y++)
	//	for(int x=-1;x<=1;x++)
	int y=0;
	int x=0;
		{
			sample =texture2D(mainTexture,texCoord+vec2(float(x)*1.2/windowWidth,float(y)*1.2/windowHeight)).rgb;
			sample = pow(sample, vec3(2.2));		// gamma
			sample =toneMap(sample, expo);
			color+=sample* sideCoeffs[x+1] * sideCoeffs[y+1];
		}
	
	sample = texture2D(blurTexture,texCoord).rgb;
	sample = pow(sample, vec3(2.2));		// gamma

	color *= vec3(1.0+contrast);
	color +=sample*bloomAmount;
	color= pow(color, vec3(1.0/(2.2+gamma)));		// gamma
	gl_FragColor.rgb = color;
	gl_FragColor.a = 1.0;
}


